package cn.zhj.service.impl;

import cn.zhj.domain.User;
import cn.zhj.exception.BusinessException;
import cn.zhj.mapper.UserMapper;
import cn.zhj.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
@Slf4j
public class UserServiceImpl implements IUserService {

    public static Map<String,Object> map = new ConcurrentHashMap<>();

    @Autowired
    private UserMapper userMapper;

    @Override
    public String login(User user) {
        //获取前端传递的用户名和密码
        String username = user.getUsername();
        String password = user.getPassword();
        //校验空值
        if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            throw new BusinessException("信息不能为空");
        }
        //根据用户名查询数据库：在mysql不区分大小写，java中区分【密码一定要区分大小写】
        User dbUser = userMapper.findByUsername(username);
        if(dbUser == null){
            throw new BusinessException("用户名不存在");
        }else{//用户名对了
            if(!password.equals(dbUser.getPassword())){
                throw new BusinessException("密码错误");
            }else{//用户名对了，密码也对了
                String token = UUID.randomUUID().toString();
                //保存到map - 后续每次访问服务器都要携带token，通过token获取登陆信息
                map.put(token,dbUser);
                return token;
            }
        }
    }
}
